package com.zik.rader_and_video.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.zik.rader_and_video.po.WeChatConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: zhouxy
 * @description:
 * @date: 2023-03-23 20:18
 * @operation:
 **/
@Component
public class ConfigurationService {
    private String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&";

    @Autowired
    private WeChatConfig wechatConfig;

    public JSONObject getAccessToken() {
        String requestUrl = accessTokenUrl + "appid=" + wechatConfig.getAppid() + "&secret=" + wechatConfig.getAppkey();
        String resp = HttpUtil.get(requestUrl);
        JSONObject result = JSONUtil.parseObj(resp);
        System.out.println("获取access_token:" + resp);
        return result;
    }

    /**
     * 获取用户列表
     * @param accessToken
     * @return
     */

    public JSONObject getUserList(String accessToken) {
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken+"&next_openid=";

        String resp = HttpRequest.get(requestUrl)
                .header("Content-Type", "application/json;charset=utf-8")
                .header("Accept", "application/json")
                .timeout(2000)
                .execute()
                .body();
        JSONObject result = JSONUtil.parseObj(resp);
        System.out.println("用户列表:" + resp);
        return result;
    }

    public JSONObject sendMsg(String token, String openId) {
        String requestUrl = " https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="  + token;
        Map<String,Object> content=new HashMap<>();
        JSONObject data = JSONUtil.createObj();

        data.put("user",new JSONObject().putOnce("value","zxy"));
        data.put("home",new JSONObject().putOnce("value","周xx"));
        data.put("date",new JSONObject().putOnce("value", DateUtil.now()));


        content.put("touser",openId);
        content.put("url","https://baidu.com");
        content.put("template_id","GGd3BgMVm9xlROtdCEG8bAuubr2tLS_zl7ovWbe5EGc");
        content.put("data",data);
        String s = JSONArray.toJSON(content).toString();
        String resp = HttpUtil.post(requestUrl, s.toString());
        System.out.println(content.toString());
        System.out.println(s);
        JSONObject result = JSONUtil.parseObj(resp);
        System.out.println("发送消息:" + resp);
        return result;
    }

}
